<template>
    <el-drawer v-model="visibleDrawer" :with-header="false" size="50%">
        <el-form>
            <el-form-item label="题目标题:">
                <el-input style="width:387px !important" v-model="formQuestion.title" placeholder="请输入标题"></el-input>
            </el-form-item>
            <el-form-item label="题目难度:">
                <QuestionSelector placeholder="请选择题目难度" v-model="formQuestion.difficulty" style="width:387px !important"
                    width="100%">
                </QuestionSelector>
            </el-form-item>
            <el-form-item label="时间限制（单位毫秒）:">
                <el-input style="width:300px !important" v-model="formQuestion.timeLimit"
                    placeholder="请输入时间限制"></el-input>
            </el-form-item>
            <el-form-item label="空间限制（单位字节）:">
                <el-input style="width:300px !important" v-model="formQuestion.spaceLimit"
                    placeholder="请输入空间限制"></el-input>
            </el-form-item>
            <el-form-item label="题目内容:">
                <div class="editor">
                    <quill-editor placeholder="请输入题目内容" v-model:content="formQuestion.content" content-type="html">
                    </quill-editor>
                </div>
            </el-form-item>
            <el-form-item label="题目用例:">
                <el-input style="width:387px !important" v-model="formQuestion.questionCase" placeholder="请输入题目用例">
                </el-input>
            </el-form-item>
            <el-form-item label="默认代码块:">
                <CodeEditor @update:value="handleEditorContent" ref="defaultCodeRef">
                </CodeEditor>
            </el-form-item>
            <el-form-item label="main函数:">
                <CodeEditor @update:value="handleEditorMainFunc" ref="mainFucRef">
                </CodeEditor>
            </el-form-item>
            <el-form-item>
                <el-button class="question-button" type="primary" plain @click="onSubmit()">发布</el-button>
            </el-form-item>
        </el-form>
    </el-drawer>
</template>

<script setup>
import { QuillEditor } from '@vueup/vue-quill'
import '@vueup/vue-quill/dist/vue-quill.snow.css'
import CodeEditor from './CodeEditor.vue'
import QuestionSelector from './QuestionSelector.vue';
import { ref, reactive } from 'vue';
import questionService from '@/apis/question-service';


async function onOpen(questionId) {
    try {
        // 打开抽屉组件
        visibleDrawer.value = true;

        // 初始化表单
        for (const key in formQuestion) {
            if (formQuestion.hasOwnProperty(key)) {
                formQuestion[key] = '';
            }
        }

        if (!questionId) return;

        // 获取问题详情数据
        const questionDetail = await questionService.getQuestionDetail(questionId);
        if (questionDetail.data === null) {
            throw new Error('获取详细信息失败：questionDetail is null');
        }

        // 将问题详情数据赋值给表单
        Object.assign(formQuestion, questionDetail.data);

        // 将默认代码和主函数代码设置到子模块中，以便在 Ace 编辑器中显示
        defaultCodeRef.value.setAceCode(formQuestion.defaultCode)
        mainFucRef.value.setAceCode(formQuestion.mainFuc)
    }
    catch (error) {
        ElMessage.error(error.message)
        return;
    }
}



function validate() {
    let msg = ''
    if (!formQuestion.title) {
        msg = '请添加题目标题'
    } else if (formQuestion.difficulty == '') {
        msg = '请选择题目难度'
    } else if (!formQuestion.timeLimit) {
        msg = '请输入时间限制'
    } else if (!formQuestion.spaceLimit) {
        msg = '请输入空间限制'
    } else if (!formQuestion.content) {
        msg = '请输入题目内容信息'
    } else if (!formQuestion.questionCase) {
        msg = '请输入题目用例名称'
    } else if (!formQuestion.defaultCode) {
        msg = '请输入默认代码'
    } else if (!formQuestion.mainFuc) {
        msg = '请输入main函数'
    } else {
        msg = ''
    }
    return msg

}

// 提交表单事件处理函数
async function onSubmit() {

    // 校验表单，获取错误信息（如果有）
    const errorMessage = validate()
    if (errorMessage) {
        ElMessage.error(errorMessage);
        return false
    }

    // 保存表单数据
    const fd = new FormData()
    for (let key in formQuestion) {
        fd.append(key, formQuestion[key])
    }

    if (formQuestion.questionId) {
        // 编辑题目请求
        await questionService.editQuestion(fd)
        ElMessage.success('编辑成功')

        // 通知父组件
        emit('success', 'edit')
    } else {
        // 添加题目请求
        await questionService.addQuestion(fd)
        ElMessage.success('添加成功')

        // 通知父组件
        emit('success', 'add')
    }

    // 添加成功后关闭抽屉
    visibleDrawer.value = false
}

// 处理子组件传递的更新内容
function handleEditorContent(content) {
    formQuestion.defaultCode = content
}

function handleEditorMainFunc(content) {
    formQuestion.mainFuc = content
}

// 注册一个发射事件，给父组件
const emit = defineEmits(['success'])
const formQuestion = reactive({
    questionId: '',
    title: '',
    difficulty: '',
    content: '',
    questionCase: '',
    timeLimit: '',
    spaceLimit: '',
    defaultCode: '',
    mainFuc: ''
})
const defaultCodeRef = ref()
const mainFucRef = ref()
const visibleDrawer = ref(false)

// defineExpose 用于暴露 onOpen 函数，允许外部调用。
defineExpose({ onOpen })

</script>

<style lang="scss">
.question-button {
    width: 200px;
}
</style>